<template>
  <div class="main-content" style="padding-top: 60px">
    <div style="display: flex; grid-gap: 20px">
      <!-- 好友列表 -->
      <div
        class="card"
        style="
          width: 20%;
          height: 597px;
          overflow-y: auto;
          overflow-x: hidden;
          background-color: #f5f7fa;
        "
      >
        <h2>好友列表</h2>
        <div
          style="
            text-align: left;
            margin-top: 10px;
            padding-top: 10px;
            height: 545px;
          "
        >
          <!-- 开始 -->
          <div
            style="
              display: flex;
              border-bottom: 2px solid #1890ff;
              margin-bottom: 12px;
            "
            v-for="item in friends"
            :key="item.userId"
          >
            <div style="flex: 1">
              <el-image
                style="width: 50px; height: 50px"
                :src="item.avatar"
                :preview-src-list="[item.avatar]"
              />
            </div>
            <div style="flex: 1; padding: 10px">
              <h3>{{ item.realName }}</h3>
            </div>
            <div style="display: flex; grid-gap: 5px; padding: 4px">
              <!-- icon -->
              <div class="socialAndSocial">
                <i
                  class="el-icon-chat-line-square"
                  :class="{ active: this.showChatFlag === item.userId }"
                  style="font-size: 40px"
                  @click="showChat(item.userId, item.realName, item.avatar)"
                ></i>
              </div>
              <div class="socialAndSocial">
                <i
                  class="el-icon-s-help"
                  :class="{ active: this.selectCircleFlag === item.userId }"
                  style="font-size: 40px"
                  @click="selectPostById(item.userId)"
                ></i>
              </div>
            </div>
          </div>
          <!-- 结束 -->
        </div>
      </div>
      <!-- 圈子详情 -->
      <div
        class="card"
        style="
          width: 80%;
          height: 597px;
          overflow-y: auto;
          overflow-x: hidden;
          text-align: left;
        "
      >
        <div style="width: 100%; height: 40%; margin-bottom: 30px">
          <el-image
            style="width: 100%; height: 100%"
            :src="circlebg"
            fit="fill"
          />
        </div>
        <!-- 帖子 -->
        <div style="width: 100%; height: 60%">
          <div
            v-for="item in posts"
            :key="item.postId"
            style="
              padding: 10px;
              border: 2px solid #1890ff;
              border-radius: 10px;
              margin-bottom: 26px;
            "
            @click="push(item.postId)"
          >
            <div style="display: flex; grid-gap: 15px">
              <div style="flex: 1">
                <div class="oneline petForumTitle" @click="push(item.postId)">
                  {{ item.title }}
                </div>
                <div
                  style="
                    color: #666;
                    margin-top: 10px;
                    font-size: 14px;
                    line-height: 1.4em;
                    height: 2.8em;
                  "
                  class="towline"
                >
                  {{ item.introduction }}
                </div>
                <div
                  style="
                    display: flex;
                    align-items: flex-start;
                    margin-top: 10px;
                  "
                >
                  <div style="flex: 1; font-size: 12px; display: flex">
                    <span style="flex: 1" class="oneline">
                      <i class="el-icon-user"></i>{{ item.realName }}
                    </span>
                    <span style="flex: 1" class="oneline">
                      <i class="el-icon-view"></i>{{ item.views }}
                    </span>
                    <span style="flex: 1" class="oneline">
                      <!-- 同样的方式处理其他的 span -->
                      <i class="el-icon-star-off"></i>{{ item.favorites }}
                    </span>
                    <span style="flex: 1" class="oneline">
                      <!-- 同样的方式处理其他的 span -->
                      <i class="el-icon-like"></i>{{ item.likes }}
                    </span>
                  </div>

                  <div
                    style="width: fit-content; margin-top: -5px"
                    class="oneline"
                  >
                    <el-tag
                      type="primary"
                      v-for="(item1, index) in JSON.parse(item.tag)"
                      :key="index"
                      style="margin-right: 10px; font-size: 12px"
                      >{{ item1 }}</el-tag
                    >
                  </div>
                </div>
              </div>
              <div style="width: 175px">
                <img
                  style="width: 100%; height: 100px; border-radius: 5px"
                  :src="item.mediaLink"
                  alt=""
                />
              </div>
            </div>
            <div style="display: flex">
              <div style="text-align: left; flex: 1">
                <el-image
                  :src="item.avatar"
                  style="border-radius: 50%; width: 30px; height: 30px"
                ></el-image>
              </div>
              <div style="text-align: right; padding: 10px">
                <p>
                  <i class="el-icon-date" style="margin-right: 4px"></i
                  >{{ item.postDate }}
                </p>
              </div>
            </div>
          </div>
          <div
            v-if="posts.length === 0"
            style="
              padding: 20px 0;
              display: flex;
              align-items: center;
              justify-content: center;
              height: 100%;
            "
          >
            <el-empty :image-size="0" />
          </div>
        </div>
        <!-- 聊天对话框 -->
        <div>
          <el-dialog
            v-model="dialogVisible"
            :title="title"
            :width="800"
            top="2vh"
            :before-close="handleClose"
          >
            <div
              style="
                background-color: #666;
                margin-top: -30px;
                border-radius: 5%;
                height: 552px;
              "
            >
              <div
                class="chat-list"
                ref="chatList"
                style="height: 420px; overflow-y: auto"
              >
                <div
                  v-for="(item, index) in chats"
                  :key="index"
                  :class="[
                    item.senderId == friendId
                      ? 'chat-list-left'
                      : 'chat-list-right',
                  ]"
                >
                  <img
                    :src="
                      item.senderId == friendId
                        ? this.friendAvatar
                        : this.loginAvatar
                    "
                    class="list-img"
                  />
                  <div
                    :class="
                      item.senderId == friendId ? 'left-msg' : 'right-msg'
                    "
                    style="padding: 5px"
                  >
                    <!-- 判断消息内容是否是图片链接 -->
                    <template v-if="isImage(item.message)">
                      <img
                        :src="item.message"
                        style="max-width: 100px; max-height: 100px"
                      />
                    </template>
                    <template v-else>
                      {{ item.message }}
                    </template>
                  </div>
                </div>
              </div>
              <div style="padding: 10px">
                <el-input
                  type="textarea"
                  :rows="3"
                  placeholder="Please input"
                  v-model="text"
                />
                <div style="text-align: right; margin-top: 5px">
                  <single-upload
                    v-model="text"
                    style="float: left; margin-left: -60px"
                  ></single-upload>
                  <el-button type="primary" @click="send()"> 发送 </el-button>
                </div>
              </div>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
//请求
import request from "@/utils/request";
import { socket } from "@/utils/websocket";
import { emitter } from "@/utils/websocket";
import SingleUpload from "@/components/upload/singleUpload";

export default {
  name: "SocialCircle",
  components: { SingleUpload },
  data() {
    return {
      friends: [],
      posts: [],
      selectCircleFlag: null,
      showChatFlag: null,
      circlebg: require("@/assets/socialBg.jpg"),
      dialogVisible: false,
      text: null, //消息内容
      title: "聊天框",
      chats: [], //聊天消息
      friendAvatar: null, //好友头像
      friendId: 0, //好友id
      loginAvatar: JSON.parse(sessionStorage.getItem("user")).avatar,
      chat: {
        receiverId: 0,
        message: "",
      },
    };
  },
  mounted() {
    //登陆
    this.loginWebSockect();
  },
  created() {
    this.load();
    //监听
    emitter.on("websocketMessage", this.handleWebSocketMessage);
  },
  beforeUnmount() {
    //销毁监听
    emitter.off("websocketMessage", this.handleWebSocketMessage);
  },
  watch: {},
  methods: {
    //登陆
    loginWebSockect() {
      Promise.resolve()
        .then(() => {
          socket.init();
        })
        .then(() => {
          socket.send({
            loginUserId: JSON.parse(sessionStorage.getItem("user")).userId,
            type: 1,
          });
        });
    },
    //接受到发送后消息的处理
    handleWebSocketMessage(msg) {
      console.log("msg:" + msg);
      request.get("/chat/listChat?userId=" + this.friendId).then((res) => {
        this.chats = res.data;
        this.$nextTick(() => {
          this.scrollToBottom(); // 调用滚动到底部方法
        });
      });
    },
    //加载初始数据
    load() {
      request.get("/chat/getFriends").then((res) => {
        this.friends = res.data;
      });
      request.get("/chat/listFriendsPosts").then((res) => {
        this.posts = res.data;
      });
    },
    //导航到
    push(postId) {
      this.$router.push(`/user/postDetail?postId=${postId}`);
    },
    //加载好友帖子数据
    selectPostById(userId) {
      if (this.selectCircleFlag === userId) {
        this.selectCircleFlag = null;
        request.get("/chat/listFriendsPosts").then((res) => {
          this.posts = res.data;
        });
      } else {
        this.selectCircleFlag = userId;
        request.get("/chat/listFriendsPosts?friendId=" + userId).then((res) => {
          this.posts = res.data;
        });
      }
    },
    //打开聊天框，并展示聊天消息
    showChat(userId, realName, friendAvatar) {
      this.showChatFlag = userId;
      this.friendId = userId;
      this.friendAvatar = friendAvatar;
      this.title = realName + "的聊天框";
      this.dialogVisible = true;
      request.get("/chat/listChat?userId=" + userId).then((res) => {
        this.chats = res.data;
        this.$nextTick(() => {
          this.scrollToBottom(); // 调用滚动到底部方法
        });
      });
    },
    //聊天框关闭后的处理
    handleClose() {
      this.showChatFlag = null;
      this.dialogVisible = false;
    },
    //发送消息
    send() {
      this.chat.receiverId = this.friendId;
      this.chat.message = this.text;
      request
        .post("/chat", this.chat)
        .then((res) => {
          if (res.code === 0) {
            this.$message.success("发送成功");
            this.text = null;
            request
              .get("/chat/listChat?userId=" + this.friendId)
              .then((res) => {
                this.chats = res.data;
                this.$nextTick(() => {
                  this.scrollToBottom(); // 调用滚动到底部方法
                });
              });
          } else {
            this.$message.success("发送失败");
          }
        })
        .then(() => {
          //websoctet向另一端的好友发送，告知有新消息啦
          socket.send({
            from: JSON.parse(sessionStorage.getItem("user")).userId,
            receiverId: this.friendId,
            type: 2,
          });
        });
    },
    scrollToBottom() {
      let chatList = this.$refs.chatList;
      // 确保 chatList 存在
      if (chatList) {
        // 将滚动条滚动到底部
        chatList.scrollTop = chatList.scrollHeight;
      }
    },
    isImage(url) {
      // 判断是否是图片链接，可以根据链接的后缀来判断
      return /\.(jpg|png|gif|jpeg)$/.test(url);
    },
  },
};
</script>

<style scoped>
.main-content {
  width: 85%;
  margin: 5px auto;
}
.card {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
}
.socialAndSocial {
  cursor: pointer;
}
.socialAndSocial:hover {
  color: #17e428;
}
.socialAndSocial .active {
  color: #1890ff; /* 设置为蓝色 */
}
.petForumTitle {
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
}
.petForumTitle:hover {
  color: #1890ff;
}
/* 超双行省略 */
.towline {
  word-break: break-all;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 超出几行省略 */
  overflow: hidden;
}
/* 超单行省略 */
.oneline {
  word-break: break-all;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1; /* 超出几行省略 */
  overflow: hidden;
}
.list-img {
  width: 40px;
  height: 40px;
  border-radius: 5px;
}
chat-list {
  display: flex;
  flex-direction: column;
}
.chat-list-left {
  padding: 20px;
  display: flex;
  flex-direction: row;
}
.chat-list-right {
  padding: 20px;
  display: flex;
  flex-direction: row-reverse;
}
.list-img {
  width: 40px;
  height: 40px;
  border-radius: 5px;
}
.left-msg {
  margin-left: 5px;
  background-color: #ffffff;
  font-size: 15px;
  border-radius: 6px;
  max-width: 200px;
  word-wrap: break-word;
}
.right-msg {
  margin-right: 7px;
  background-color: #46a6ff;
  font-size: 15px;
  border-radius: 6px;
  max-width: 200px;
  word-wrap: break-word;
}
::-webkit-scrollbar-track {
  background-color: transparent; /* 或者与父元素相同的颜色 */
}
</style>
